package com.nut.spp.adapy;

import com.alibaba.fastjson.JSON;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.*;
import com.nut.spp.adapy.req.CreateReq;
import com.nut.spp.common.Result;
import com.nut.spp.util.IdUtil;
import com.nut.spp.util.MathUtil;
import com.nut.spp.util.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * doc https://docs.adapay.tech/api/index.html
 * <p>
 * 1、用户开户（同一个人第一次开户调用）：
 * 创建实名用户对象：https://doc.adapay.tech/document/api/#/member?id=%e5%88%9b%e5%bb%ba%e5%ae%9e%e5%90%8d%e7%94%a8%e6%88%b7%e5%af%b9%e8%b1%a1
 * 2、绑快捷卡（同一张卡第一次绑定调用）：
 * 绑卡发送短信--创建快捷绑卡申请：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e7%bb%91%e5%8d%a1%e7%94%b3%e8%af%b7
 * 绑卡验证短信验证码--创建快捷绑卡确认：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e7%bb%91%e5%8d%a1%e7%a1%ae%e8%ae%a4
 * 3、快捷支付：
 * 支付发送短信--创建支付对象：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e6%94%af%e4%bb%98%e5%af%b9%e8%b1%a1
 * 支付验证短信验证码--创建快捷支付确认：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e6%94%af%e4%bb%98%e7%a1%ae%e8%ae%a4
 */
@Service
@Slf4j
public class AdapayClient {

    /**
     * 初始化商户配置，服务器启动前，必须通过该方式初始化商户配置完成
     * apiKey为prod模式的API KEY
     * mockApiKey为mock模式的API KEY
     * rsaPrivateKey为商户发起请求时，用于请求参数加签所需要的RSA私钥
     */
    public static final String apiKey = "api_live_3d863679-ee8b-44b6-a970-74efc044f06b";
    public static final String mockApiKey = "api_test_d68ca3dc-7bfe-4220-b8c9-08ad7dc1495c";
    public static final String rsaPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIWsk/KqgvAeHsEAk8CxnWdXiZYAHLsZVu28AU2BK0cdMG/2x0wCIixvvG6cOPXcc+DpF8XgSHxYN5l5hZa0RPfg9iZPBZWQFH9Lpl4+sXlylZRSRFU6VfPzruvuzM3rREJHMieqg1/W6HpjYX4j/M+GE0iWMcMjplM91WT6Fd6zAgMBAAECgYBxPy3wLijUCJCBbl2+qDrz7CNx4xJ0KBmPOvHXmZDypHX+xRE/Aae2Acuf4dYX5PZ/Grq7NzHxtkMUUPGuJXcvUbU52sC1nXn2ZFp4bC3BG4DfBKPL8w/uDljAmJqCeWKHVuMYkI0bA4kdvNludSMjmVXbt0hMOTQjiMnbu2GTgQJBAOIAkihpwmqIN64GaseV8YM6FuSulxkQJx3vCtiYBWhNU7OQKf5N1NbYEZ4xgrNBtu3Q61SEjF4y6RP1GlWAk+ECQQCXar//3cQ8CpQ3xMKNEo/LkY25jsS6iSPd6oZQBTRGfCJZaj1lNrwL/KtSjtRIbze0xltjduH7M6KKPDD7l4UTAkBqCXSKC50RWNovB4nAHSUUugOVxijUtJR14ftHxoP6/RUBkelyDNiI+RXDEF3Pd0y55iUUIaCubdqX5480gMBhAkBFTiI1jh8c0EbJQ/E8uwtARQ4WqcdYDh9xmsABbnBf9r+OJ7eUVTo7TlpofmGiCe34e3YnD6od3aN/HE/bSJ4rAkBcLJ1uouoDVZar2BNp1gCs6RLkpj7bZ7oPZBXxNDTw5eDsINc0tKdXRHBcXrMNCi3zqopr56wBJEg/+2JWkLG4";
    public static final String appId = "app_4a6f810d-482b-498b-be39-27a0b4cda0a5";
    public static final String callbackUrl = "https://xxxx.com/xxxx";

    public static final String status = "status";
    public static final String errorMsg = "error_msg";

    public AdapayClient() {

        /**
         * debug 模式，开启后有详细的日志
         */
        Adapay.debug = true;

        /**
         * prodMode 模式，默认为生产模式，false可以使用mock模式
         */
        Adapay.prodMode = true;

        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);

        try {
            Adapay.initWithMerConfig(merConfig);
        } catch (Exception e) {
            log.error("pay_init_error", e);
        }
    }

    /**
     * 创建实名用户对象
     * 创建实名用户对象：https://doc.adapay.tech/document/api/#/member?id=%e5%88%9b%e5%bb%ba%e5%ae%9e%e5%90%8d%e7%94%a8%e6%88%b7%e5%af%b9%e8%b1%a1
     *
     * @param memberId
     * @param name
     * @param mobile
     * @param ident
     * @return
     */
    public Result createRealName(String memberId, String name, String mobile, String ident) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("adapay_func_code", "members.realname");
            map.put("member_id", memberId);
            map.put("tel_no", mobile);
            map.put("user_name", name);
            map.put("cert_type", "00");
            map.put("cert_id", ident);
            map.put("app_id", appId);

            Map<String, Object> resp = AdapayCommon.requestAdapay(map);

            if (resp.get(status).toString().equals("succeeded")) {
                return Result.ok();
            }

            return Result.fail(resp.get(errorMsg).toString());
            //{"data":"{\"app_id\":\"app_4a6f810d-482b-498b-be39-27a0b4cda0a5\",\"cert_id\":\"330802198411293215\",\"cert_type\":\"00\",\"created_time\":\"1751671680\",\"disabled\":\"N\",\"identified\":\"Y\",\"member_id\":\"25022606074271\",\"object\":\"member\",\"tel_no\":\"15157009867\",\"user_name\":\"张明俊\",\"status\":\"succeeded\",\"prod_mode\":\"true\"}","signature":"IxculWvFlwn/MBM7d60aN2b62IP2w6YE4gDD9kF9bKyzpm/h6lDLRcy33XQFQ1oIP94z/HhwyYyW5Ardcz8Vc/GeZLDyT529RX9sBNIjfP6U+q08kh00t/lPgSBepFOJ8jhkRyPs/UpNgIcXwosv0guNssEkNybcdKD2iokbnWw="}

//            String status = member.get("status").toString();
//            if (status.equals("success")) {
//                return;
//            }

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }


    /**
     * 创建快捷绑卡申请
     * 绑卡发送短信--创建快捷绑卡申请：
     * https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e7%bb%91%e5%8d%a1%e7%94%b3%e8%af%b7
     *
     * @param memberId
     * @param cardId
     * @param mobile
     * @return
     */
    public Result cardApply(String memberId, String cardId, String mobile) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("member_id", memberId);
            map.put("card_id", cardId);
            map.put("tel_no", mobile);
//            map.put("vip_code", code);
            map.put("app_id", appId);
            Map<String, Object> resp = FastPay.cardApply(map);

//            succeeded：成功
//            failed：失败
//            pending：处理中
            if (resp.get(status).toString().equals("succeeded")) {
                return Result.ok();
            }

            return Result.fail(resp.get(errorMsg).toString());

//            post back={"data":"{\"app_id\":\"app_4a6f810d-482b-498b-be39-27a0b4cda0a5\",\"card_id\":\"6228481078********6\",\"created_time\":\"1751671858\",\"error_code\":\"bind_card_send_sms_error\",\"error_msg\":\"通过支付类型未路由到网关信息！\",\"error_type\":\"api_error\",\"id\":\"0787352994846416896\",\"member_id\":\"25022606074271\",\"mer_cust_id\":\"0494410373985152\",\"object\":\"fast_card\",\"prod_mode\":\"true\",\"status\":\"failed\",\"tel_no\":\"1515700****\"}","signature":"BYJqIqE/kKOQgMMx5dqHIFbZ4Lp1EzahT6OwZWK7d4+pyjAYJNEyxs6CsycONXCqtEVfxxilAZhnJoAu1uvnTfg1zVuXUcIPdGzB9p4z2rPc8ZZXJl3yCeWrO4IjWuMEUPhWMD1pX9sZQs1rxc715ckcngovRElEVXVD8sO+nxI="}
//            String applyId = resp.get("status").toString();
//            String errorMsg = resp.get("error_msg").toString();
//            System.out.println(applyId);

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }

    /**
     * 创建快捷绑卡确认
     * 绑卡验证短信验证码--创建快捷绑卡确认：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e7%bb%91%e5%8d%a1%e7%a1%ae%e8%ae%a4
     *
     * @param applyId
     * @param code
     * @return
     */
    public Result cardConfirm(String applyId, String code) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("apply_id", applyId);
            map.put("sms_code", code);
            map.put("notify_url", callbackUrl);
            map.put("app_id", appId);
            Map<String, Object> resp = FastPay.cardConfirm(map);

            if (resp.get(status).toString().equals("succeeded")) {
                return Result.ok();
            }

            return Result.fail(resp.get(errorMsg).toString());

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }

    /**
     * 查询快捷卡对象列表
     *
     * @param memberId
     * @param tokenNo
     * @return
     */
    public Result cardList(String memberId, String tokenNo) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("member_id", memberId);
//            map.put("token_no", tokenNo);
            map.put("app_id", appId);

            Map<String, Object> resp = FastPay.cardList(map);

//            {
//                "data": "{\"app_id\":\"app_4a6f810d-482b-498b-be39-27a0b4cda0a5\",\"has_more\":false,\"member_id\":\"25022606074271\",\"mer_cust_id\":\"0494410373985152\",\"object\":\"list\",\"prod_mode\":\"true\",\"status\":\"succeeded\"}",
//                    "signature": "kt/DZe661ce5vMO4zs2lFnjQ7B3RLbA4FWZlmq0xo1rAR3sz4mShOh0FGlmiRFwDcWw3KdLR2JqgIremFRIWWDHCz/cfv8qcbpyzj9G6k0GORtS6T5F+wIJOU9fXAdSXG9oG1GPSOLCsc9izsQFoEQN1gR0dl2+AfyqYOAx1mvQ="
//            }
            System.out.println(resp);

            if (resp.get(status).toString().equals("succeeded")) {
                return Result.ok();
            }

            return Result.fail(resp.get(errorMsg).toString());

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }

    /**
     * 创建支付对象
     * 支付发送短信--创建支付对象：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e6%94%af%e4%bb%98%e5%af%b9%e8%b1%a1
     *
     * @param paymentId
     * @param smsCode
     * @return
     */
    public Map<String, Object> confirm(String paymentId, String smsCode) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("payment_id", paymentId);
            map.put("sms_code", smsCode);
            map.put("app_id", appId);
            Map<String, Object> result = FastPay.confirm(map);

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }

    /**
     * 创建快捷支付短信重发
     * 支付验证短信验证码--创建快捷支付确认：https://doc.adapay.tech/document/api/#/payment?id=%e5%88%9b%e5%bb%ba%e5%bf%ab%e6%8d%b7%e6%94%af%e4%bb%98%e7%a1%ae%e8%ae%a4
     *
     * @param paymentId
     * @return
     */
    public Map<String, Object> smsCode(String paymentId) {

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("payment_id", paymentId);
            Map<String, Object> result = FastPay.smsCode(map);

        } catch (BaseAdaPayException e) {
            log.error("pay_create_real_name_error", e);
        }
        return null;
    }


    public Map<String, Object> create(CreateReq req) {

        Map<String, Object> paramMap = new HashMap<>(10);

        paramMap.put("app_id", appId);
        paramMap.put("order_no", req.getSsn());
//        paramMap.put("pay_channel", "alipay");
//        paramMap.put("pay_channel", "alipay_qr");

//        paramMap.put("notify_url", "http://19ad5c3e.r12.cpolar.top/system/callback");
//        paramMap.put("notify_url", "http://e079fc3.r8.cpolar.top/system/callback");
        paramMap.put("notify_url", req.getCallback());


        Integer payWay = req.getPayWay();
        String payChannel = null;
//        alipay_qr  支付宝扫码   wx_pub 微信扫码
        if (payWay == 1) {
            payChannel = "alipay_qr";
        } else if (payWay == 2) {
            payChannel = "wx_pub";
            HashMap<String, Object> map = new HashMap<>();
            map.put("open_id", req.getOpenid());
            paramMap.put("expend", map);
        } else if (payWay == 4) {
            payChannel = "fast_pay";
        }

        String authCode = req.getAuthCode();
        if (StringTool.isNotEmpty(authCode)) {

            HashMap<String, Object> map = new HashMap<>();
            map.put("auth_code", authCode);
            paramMap.put("expend", map);

            String start = authCode.substring(0, 2);
//            支付宝：25~30开头的长度为16~24位的数字。 例如：289431869362714645；
//            微信：18位纯数字，以10、11、12、13、14、15开头 。例如：135112298638468293

            if (start.equals("25") || start.equals("26") || start.equals("27") || start.equals("28") || start.equals("29") || start.equals("30")) {
                payChannel = "alipay_scan";
            } else if (start.equals("10") || start.equals("11") || start.equals("12") || start.equals("13") || start.equals("14") || start.equals("15")) {
                payChannel = "wx_scan";
            }

        }

//        paramMap.put("pay_channel", payChannel);

        paramMap.put("pay_channel", "fast_pay");

        String amount = MathUtil.toYuan2f(req.getPayMoney());
//        String amount = "0.01";
        log.info("amount=" + amount);
//        paramMap.put("pay_amt", "0.01");
        paramMap.put("pay_amt", amount);

        paramMap.put("goods_title", req.getSubject());
        paramMap.put("goods_desc", req.getBody());

        Map<String, Object> payment = new HashMap<>();
        try {
            log.info("pay_create_req=" + JSON.toJSONString(paramMap));
            payment = Payment.create(paramMap);
        } catch (BaseAdaPayException e) {
            log.error("pay_create_error", e);
        }
        log.info("pay_create_resp=" + JSON.toJSONString(payment));

//        Map<String, String> expendMap = (Map<String, String>) payment.get("expend");
//        String qrcodeUrl = expendMap.get("qrcode_url");
//        System.out.println(qrcodeUrl);

//        {"order_no":"c3a2b3ac8087443b8e21fb41994db6f2","created_time":"1688609321","party_order_id":"02212307063652155505829","pay_amt":"0.01","expend":{"qrcode_url":"https://qr.alipay.com/bax02498rlxkgnmg1nsw25a3"},"prod_mode":"true","pay_channel":"alipay_qr","query_url":"https://api.adapay.tech/v1/expire/payments/1/9886382e8e3532ce40c0ea575d9df03c","id":"002212023070610084110522849544420143104","app_id":"app_4a6f810d-482b-498b-be39-27a0b4cda0a5","object":"payment","status":"succeeded"}

        return payment;
    }

    /**
     * 执行一个退款交易
     *
     * @param paymentId 要退款的原支付paymentId
     * @return 创建的退款对象
     * @throws Exception 异常
     */
    public Map<String, Object> refund(String paymentId, Integer money) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String amount = MathUtil.toYuan2f(money);
        log.info("amount=" + amount);
        paramMap.put("refund_amt", amount);
        paramMap.put("app_id", appId);
        paramMap.put("refund_order_no", IdUtil.generateSsn());
        Map<String, Object> refund = null;
        try {
            log.info("refund_create_req=" + JSON.toJSONString(paramMap));
            refund = Refund.create(paymentId, paramMap);
        } catch (BaseAdaPayException e) {
            log.error("refund_create_error", e);
        }
        log.info("refund_create_resp=" + JSON.toJSONString(refund));

        //{"payment_order_no":"1689404905670876","created_time":"1689591288000","reason":"","refund_amt":"0.01","notify_url":"","payment_id":"002212023071515082510526186466796187648","prod_mode":"true","channel_no":"2023071721R3revt","succeed_time":"1689591288000","id":"0022120230717185447980526968208421167104","app_id":"app_4a6f810d-482b-498b-be39-27a0b4cda0a5","refund_order_no":"1689591268760992","fee_amt":"0.00","object":"refund","status":"pending"}
        return refund;
    }

    public static void main(String[] args) {

        System.out.println("1234".substring(0, 2));

        System.out.println("002212023071515082510526186466796187648".length());

        BigDecimal bigDecimal = BigDecimal.valueOf(1L);

        String format = String.format("%.2f", bigDecimal);
        System.out.println(format);
    }
}